

set(LDD_HACK_LOCATION ${CMAKE_CURRENT_LIST_DIR}/ldd_hack.cpp)
#
# add_arduino_core function
#
function(add_arduino_core)
  if( NOT ARDUINO_PLATFORM)
    message(FATAL_ERROR "ARDUINO_PLATFORM not set.  Can't build libraries without it!")
  endif()
  if( ARDUINO_LIBS)
    message(FATAL_ERROR "Reinclusion of function add_arduino_core().")
  endif()
  message(STATUS "Adding arduino_core library")
  # find the core files and remove main.cpp!  (Main is used for sketches, but we aren't writing sketches...
  # then build

  foreach(dir_ ${ARDUINO_INCLUDE_DIR})
    file(GLOB temp_source_
      ${dir_}/*.c*
      ${dir_}/*.h*
      )
    set(source_ ${source_} ${temp_source_})
  endforeach()
  if( NOT ARDUINO_USE_MAIN)
    list(REMOVE_ITEM source_ "${ARDUINO_INCLUDE_DIR}/main.cpp")
  endif()
  include_directories(${ARDUINO_INCLUDE_DIR})
  add_library(arduino_core ${source_} ${LDD_HACK_LOCATION})

  set(ARDUINO_LIBS arduino_core PARENT_SCOPE)
endfunction()

#
# add_arduino_component function
#
# Adds the component library to ARDUINO_LIBS and the include dir to ARDUINO_INCLUDE_DIR
function(add_arduino_component lib_)
  # insure core libraries exist, add if not and provide dev warning
  if( NOT ARDUINO_LIBS)
    message(AUTHOR_WARNING "add_arduino_component(x) called without/before call to add_arduino_core().  Doing it ourselves... ")
    add_arduino_core()
  endif()

  message(STATUS "Adding ${lib_} library")
  # set the dir, and then test for the correct header file, set an error on failure (although this should MAYBE be a warning)
  set( mydir_ ${ARDUINO_EXTRA_LIB_DIR}/${lib_})
  find_path(testpath_ ${lib_}.h ${lib_}.hpp
    PATHS
      ${mydir_}
    )
  if(NOT testpath_)
    message(FATAL_ERROR "Could not find Arduino library: ${lib_}")
  endif()
  # add the source, don't forget the utility directory!
  file(GLOB source_
    ${mydir_}/*.c*
    ${mydir_}/*.h*
    ${mydir_}/utility/*.c*
    ${mydir_}/utility/*.h*
    )

  include_directories(${mydir_} ${mydir_}/utility)
  add_library(${lib_} ${source_})

  # set the variables, make sure arduino core is the last entry
  set( ARDUINO_LIBS ${lib_} ${ARDUINO_LIBS} PARENT_SCOPE)
  set( ARDUINO_INCLUDE_DIR ${ARDUINO_INCLUDE_DIR} ${mydir_} PARENT_SCOPE)
endfunction()

